<?php
session_start();
require_once 'db_connect.php';
require_once 'HerbManager.php';

// 检查用户是否已登录
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$herbManager = new HerbManager();
$herbs = $herbManager->getAllHerbs();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>中药材管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.0/font/bootstrap-icons.css">
    <style>
        .herb-card {
            transition: all 0.3s;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .herb-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 15px rgba(0,0,0,0.1);
        }
        .prescription-item {
            border-bottom: 1px dashed #ddd;
            padding: 12px 0;
        }
        .herb-detail {
            background-color: #f8f9fa;
            border-left: 4px solid #28a745;
            padding: 15px;
            border-radius: 0 5px 5px 0;
        }
        .search-highlight {
            background-color: #fff3cd;
            font-weight: bold;
        }
        .price-badge {
            font-size: 0.9rem;
            padding: 5px 10px;
        }
        .header-bg {
            background: linear-gradient(135deg, #2e7d32 0%, #4caf50 100%);
            color: white;
            padding: 20px 0;
            margin-bottom: 30px;
            border-radius: 0 0 20px 20px;
        }
        .footer {
            margin-top: 50px;
            padding: 20px 0;
            background-color: #f8f9fa;
            border-top: 1px solid #e9ecef;
        }
        
        /* 药方计算器搜索结果显示样式 */
        #addHerbSearchResults .list-group-item {
            transition: all 0.2s ease;
        }
        
        #addHerbSearchResults .list-group-item:hover {
            background-color: #e9ecef;
            transform: translateX(5px);
        }
        
        #addHerbSearchResults .list-group-item strong {
            color: #2e7d32;
        }
        
        #addHerbSearchResults .badge {
            font-size: 0.8rem;
        }
        
        /* 药方项样式 */
        .prescription-item {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            border: 1px solid #e9ecef;
        }
        
        .prescription-item:last-child {
            margin-bottom: 0;
        }
    </style>
</head>
<body>
    <div class="header-bg">
        <div class="container">
            <div class="d-flex justify-content-between align-items-center">
                <h1 class="display-4 fw-bold">
                    <i class="bi bi-flower2"></i> 中药材管理系统
                </h1>
                <div class="d-flex align-items-center">
                    <span class="text-white me-3">
                        <i class="bi bi-person-circle"></i> 
                        欢迎，<?php echo htmlspecialchars($_SESSION['user_name'] ?? $_SESSION['user_phone']); ?>
                    </span>
                    <button class="btn btn-light me-2" data-bs-toggle="modal" data-bs-target="#addHerbModal">
                        <i class="bi bi-plus-circle"></i> 添加药材
                    </button>
                    <button class="btn btn-outline-light me-2" data-bs-toggle="modal" data-bs-target="#prescriptionModal">
                        <i class="bi bi-calculator"></i> 计算药方
                    </button>
                    <a href="logout.php" class="btn btn-outline-light">
                        <i class="bi bi-box-arrow-right"></i> 退出
                    </a>
                </div>
            </div>
            <p class="lead">查询药材功效，计算药方价格，管理药材信息</p>
        </div>
    </div>

    <div class="container">
        <!-- 搜索区域 -->
        <div class="card mb-4 shadow-sm">
            <div class="card-body">
                <div class="input-group">
                    <input type="text" id="searchInput" class="form-control form-control-lg" 
                           placeholder="输入药材名称搜索..." aria-label="搜索药材">
                    <button class="btn btn-success" type="button" id="searchButton">
                        <i class="bi bi-search"></i> 搜索
                    </button>
                </div>
            </div>
        </div>

        <!-- 药材展示区域 -->
        <div id="herbsContainer" class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4">
            <?php foreach ($herbs as $herb): 
              $pricePerGram = $herbManager->getPricePerGram($herb);
            ?>
            <div class="col" data-herb-id="<?= $herb['id'] ?>">
                <div class="card herb-card h-100">
                    <div class="card-header bg-success text-white">
                        <h5 class="card-title mb-0"><?= htmlspecialchars($herb['name']) ?></h5>
                    </div>
                    <div class="card-body">
                        <div class="d-flex justify-content-between mb-2">
                            <span class="badge bg-primary price-badge">¥<?= number_format($pricePerGram, 3) ?>/g</span>
                            <span class="badge bg-info price-badge shipping-info"><?= $herb['shipping'] === '包邮' ? '包邮' : '运费另计' ?></span>
                        </div>
                        <div class="herb-detail mb-3">
                            <p class="mb-1"><strong>功效：</strong><span class="effects-info"><?= htmlspecialchars($herb['effects'] ?: '暂无信息') ?></span></p>
                            <p class="mb-0"><strong>忌口：</strong><span class="contraindications-info"><?= htmlspecialchars($herb['contraindications'] ?: '暂无信息') ?></span></p>
                        </div>
                        <div class="price-details mb-2">
                            <small class="text-muted price-info">
                                <?php
                                $priceText = '';
                                if ($herb['sale_price']) $priceText .= '售价: ¥' . $herb['sale_price'];
                                if ($herb['purchase_price']) $priceText .= ($priceText ? ' | ' : '') . '进价: ¥' . $herb['purchase_price'];
                                if ($herb['category_price']) $priceText .= ($priceText ? ' | ' : '') . '类目价: ¥' . $herb['category_price'];
                                echo $priceText ?: '价格未设置';
                                ?>
                            </small>
                        </div>
                    </div>
                    <div class="card-footer bg-light d-flex justify-content-end">
                        <button class="btn btn-sm btn-outline-primary me-2 edit-btn" data-id="<?= $herb['id'] ?>">
                            <i class="bi bi-pencil"></i> 编辑
                        </button>
                        <button class="btn btn-sm btn-outline-danger delete-btn" data-id="<?= $herb['id'] ?>">
                            <i class="bi bi-trash"></i> 删除
                        </button>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <footer class="footer">
        <div class="container text-center">
            <p class="mb-0">中药材管理系统 © <?= date('Y') ?> - 传承中医药文化，服务健康生活</p>
        </div>
    </footer>

    <!-- 添加药材模态框 -->
    <div class="modal fade" id="addHerbModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-success text-white">
                    <h5 class="modal-title">添加新药材</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="addHerbForm" action="add_herb.php" method="POST">
                    <div class="modal-body">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">药材名称 *</label>
                                <input type="text" name="name" class="form-control" required>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">进货价(元/10g)</label>
                                <input type="number" step="0.01" name="purchase_price" class="form-control">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">售价(元/10g)</label>
                                <input type="number" step="0.01" name="sale_price" class="form-control">
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-4">
                                <label class="form-label">运费方式</label>
                                <select name="shipping" class="form-select">
                                    <option value="包邮" selected>包邮</option>
                                    <option value="按重计费">按重计费</option>
                                </select>
                            </div>
                            <div class="col-md-8">
                                <label class="form-label">类目售价(元/250g)</label>
                                <input type="number" step="0.01" name="category_price" class="form-control">
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">药材功效</label>
                            <textarea name="effects" class="form-control" rows="3"></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">忌口</label>
                            <textarea name="contraindications" class="form-control" rows="2"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-success">保存药材</button>
                    </div>
                    
                    <!-- 药方计算区域 -->
                    <div class="modal-body border-top pt-3">
                        <h6 class="text-success mb-3">
                            <i class="bi bi-calculator"></i> 药方价格计算器
                        </h6>
                        <div class="alert alert-info alert-sm mb-3">
                            <small>
                                <i class="bi bi-info-circle"></i> 
                                在添加药材的同时，您可以计算药方价格。输入药材名称，选择用量，系统会自动计算总价。
                            </small>
                        </div>
                        <div class="mb-3">
                            <div class="input-group">
                                <input type="text" id="addHerbHerbSearch" class="form-control" placeholder="输入药材名称，系统会显示搜索建议...">
                                <button class="btn btn-outline-success" type="button" id="addHerbAddToPrescription">
                                    <i class="bi bi-plus-circle"></i> 添加
                                </button>
                            </div>
                            <div id="addHerbSearchResults" class="mt-2"></div>
                        </div>
                        
                        <div class="card shadow-sm">
                            <div class="card-header bg-light">
                                <h6 class="mb-0">药方内容</h6>
                            </div>
                            <div class="card-body">
                                <div id="addHerbPrescriptionItems">
                                    <!-- 药方项将在这里动态添加 -->
                                </div>
                                
                                <hr>
                                <div class="d-flex justify-content-between align-items-center">
                                    <h6 class="mb-0">总计:</h6>
                                    <h5 class="mb-0 text-success" id="addHerbPrescriptionTotal">¥0.00</h5>
                                </div>
                                <div class="d-flex justify-content-between align-items-center mt-2">
                                    <small class="text-muted">总重量:</small>
                                    <small class="text-muted" id="addHerbPrescriptionWeight">0g</small>
                                </div>
                                <div class="text-center mt-3">
                                    <button type="button" class="btn btn-outline-secondary btn-sm" id="clearAddHerbPrescription">
                                        <i class="bi bi-trash"></i> 清空药方
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 编辑药材模态框 -->
    <div class="modal fade" id="editHerbModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-success text-white">
                    <h5 class="modal-title">编辑药材</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="editHerbForm" action="edit_herb.php" method="POST">
                    <input type="hidden" name="id" id="editHerbId">
                    <div class="modal-body">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">药材名称 *</label>
                                <input type="text" name="name" id="editHerbName" class="form-control" required>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">进货价(元/10g)</label>
                                <input type="number" step="0.01" name="purchase_price" id="editPurchasePrice" class="form-control">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">售价(元/10g)</label>
                                <input type="number" step="0.01" name="sale_price" id="editSalePrice" class="form-control">
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-4">
                                <label class="form-label">运费方式</label>
                                <select name="shipping" id="editShipping" class="form-select">
                                    <option value="包邮">包邮</option>
                                    <option value="按重计费">按重计费</option>
                                </select>
                            </div>
                            <div class="col-md-8">
                                <label class="form-label">类目售价(元/250g)</label>
                                <input type="number" step="0.01" name="category_price" id="editCategoryPrice" class="form-control">
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">药材功效</label>
                            <textarea name="effects" id="editEffects" class="form-control" rows="3"></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">忌口</label>
                            <textarea name="contraindications" id="editContraindications" class="form-control" rows="2"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-success">保存修改</button>
                    </div>
                </form>
            </div>
        </div>
        
    </div>

    <!-- 药方计算模态框 -->
    <div class="modal fade" id="prescriptionModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title">药方价格计算器</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <!-- 批量输入药方区域 -->
                    <div class="mb-4">
                        <div class="card">
                            <div class="card-header bg-success text-white">
                                <h6 class="mb-0"><i class="bi bi-clipboard-data"></i> 批量输入药方</h6>
                            </div>
                            <div class="card-body">
                                <p class="text-muted small mb-2">支持格式：药材名+用量，用逗号、空格或换行分隔</p>
                                <p class="text-muted small mb-2">自动处理：括号内容、注释等会被自动移除</p>
                                <p class="text-muted small mb-3">示例：西洋参90g,别直参60g,柴胡90g 或 西洋参90g 别直参60g 柴胡90g</p>
                                <div class="mb-3">
                                    <textarea id="batchPrescriptionInput" class="form-control" rows="4" 
                                              placeholder="请输入药方，例如：&#10;西洋参90g&#10;别直参60g&#10;柴胡90g&#10;当归90g"></textarea>
                                </div>
                                <button class="btn btn-success" type="button" id="parseBatchPrescription">
                                    <i class="bi bi-magic"></i> 解析并添加
                                </button>
                                <button class="btn btn-outline-secondary ms-2" type="button" id="clearBatchInput">
                                    <i class="bi bi-trash"></i> 清空输入
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 单个药材添加区域 -->
                    <div class="mb-3">
                        <div class="card">
                            <div class="card-header bg-primary text-white">
                                <h6 class="mb-0"><i class="bi bi-plus-circle"></i> 单个添加药材</h6>
                            </div>
                            <div class="card-body">
                                <div class="input-group">
                                    <input type="text" id="herbSearch" class="form-control" placeholder="输入药材名称...">
                                    <button class="btn btn-outline-primary" type="button" id="addToPrescription">
                                        <i class="bi bi-plus-circle"></i> 添加
                                    </button>
                                </div>
                                <div id="searchResults" class="mt-2"></div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card shadow-sm">
                        <div class="card-header bg-light">
                            <h6 class="mb-0">药方内容</h6>
                        </div>
                        <div class="card-body">
                            <div id="prescriptionItems">
                                <!-- 示例项 -->
                                <div class="prescription-item d-flex align-items-center">
                                    <div class="fw-bold me-2" style="min-width: 120px;">黄芪</div>
                                    <div class="flex-grow-1">
                                        <input type="number" class="form-control form-control-sm weight-input" 
                                               value="100" min="1" step="1" placeholder="用量(g)">
                                    </div>
                                    <div class="ms-2 text-nowrap">
                                        <span class="price-per-gram">¥0.12/g</span>
                                    </div>
                                    <div class="ms-3 text-end" style="min-width: 80px;">
                                        <span class="item-total">¥12.00</span>
                                    </div>
                                    <button class="btn btn-sm btn-outline-danger ms-3 remove-item">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </div>
                            </div>
                            
                            <hr>
                            <div class="d-flex justify-content-between align-items-center">
                                <h5 class="mb-0">总计:</h5>
                                <h3 class="mb-0 text-primary" id="prescriptionTotal">¥12.00</h3>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="calculateBtn">重新计算</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 显示提示信息
        function showAlert(type, message) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            // 插入到页面顶部
            const container = document.querySelector('.container');
            container.insertBefore(alertDiv, container.firstChild);
            
            // 3秒后自动消失
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 3000);
        }

        // 搜索功能
        document.getElementById('searchButton').addEventListener('click', function() {
            const query = document.getElementById('searchInput').value.trim();
            if (query) {
                fetch(`search.php?query=${encodeURIComponent(query)}`)
                    .then(response => response.json())
                    .then(data => {
                        let html = '';
                        if (data.length === 0) {
                            html = '<div class="alert alert-info">未找到相关药材</div>';
                        } else {
                            html = '<div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4">';
                            data.forEach(herb => {
                                const pricePerGram = calculatePricePerGram(herb);
                                html += `
                                    <div class="col">
                                        <div class="card herb-card h-100">
                                            <div class="card-header bg-success text-white">
                                                <h5 class="card-title mb-0">${highlight(herb.name, query)}</h5>
                                            </div>
                                            <div class="card-body">
                                                <div class="d-flex justify-content-between mb-2">
                                                    <span class="badge bg-primary price-badge">¥${pricePerGram.toFixed(2)}/g</span>
                                                    <span class="badge bg-info price-badge">${herb.shipping === '包邮' ? '包邮' : '运费另计'}</span>
                                                </div>
                                                <div class="herb-detail mb-3">
                                                    <p class="mb-1"><strong>功效：</strong>${herb.effects || '暂无信息'}</p>
                                                    <p class="mb-0"><strong>忌口：</strong>${herb.contraindications || '暂无信息'}</p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                `;
                            });
                            html += '</div>';
                        }
                        document.getElementById('herbsContainer').innerHTML = html;
                    });
            }
        });

        // 添加药材模态框中的药材搜索功能
        document.getElementById('addHerbHerbSearch').addEventListener('input', function() {
            const query = this.value.trim();
            const searchResults = document.getElementById('addHerbSearchResults');
            
            if (query.length < 2) {
                searchResults.innerHTML = '';
                return;
            }
            
            fetch(`search.php?query=${encodeURIComponent(query)}`)
                .then(response => response.json())
                .then(data => {
                    let html = '';
                    if (data.length === 0) {
                        html = '<div class="alert alert-info">未找到相关药材</div>';
                    } else {
                        html = '<div class="list-group">';
                        data.slice(0, 5).forEach(herb => {
                            const pricePerGram = calculatePricePerGram(herb);
                            html += `
                                <div class="list-group-item list-group-item-action d-flex justify-content-between align-items-center" 
                                     style="cursor: pointer;" onclick="selectHerbForPrescription('${herb.name}', ${pricePerGram})">
                                    <div>
                                        <strong>${herb.name}</strong>
                                        <small class="text-muted d-block">${herb.effects || '暂无功效信息'}</small>
                                    </div>
                                    <span class="badge bg-success">¥${pricePerGram.toFixed(2)}/g</span>
                                </div>
                            `;
                        });
                        html += '</div>';
                    }
                    searchResults.innerHTML = html;
                });
        });

        // 高亮显示搜索关键词
        function highlight(text, query) {
            if (!query) return text;
            const regex = new RegExp(query, 'gi');
            return text.replace(regex, match => `<span class="search-highlight">${match}</span>`);
        }

        // 计算每克价格
        function calculatePricePerGram(herb) {
            if (herb.sale_price) return herb.sale_price / 10;
            if (herb.category_price) return herb.category_price / 250;
            return (herb.purchase_price * 1.2) / 10;
        }

        // 选择药材添加到药方（在添加药材模态框中）
        function selectHerbForPrescription(herbName, pricePerGram) {
            const itemHtml = `
                <div class="prescription-item d-flex align-items-center" data-name="${herbName}">
                    <div class="fw-bold me-2" style="min-width: 120px;">${herbName}</div>
                    <div class="flex-grow-1">
                        <input type="number" class="form-control form-control-sm weight-input" 
                               value="100" min="1" step="1" placeholder="用量(g)">
                    </div>
                    <div class="ms-2 text-nowrap">
                        <span class="price-per-gram">¥${pricePerGram.toFixed(2)}/g</span>
                    </div>
                    <div class="ms-3 text-end" style="min-width: 80px;">
                        <span class="item-total">¥${(pricePerGram * 100).toFixed(2)}</span>
                    </div>
                    <button class="btn btn-sm btn-outline-danger ms-3 remove-item">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            `;
            document.getElementById('addHerbPrescriptionItems').innerHTML += itemHtml;
            updateAddHerbTotal();
            document.getElementById('addHerbHerbSearch').value = '';
            document.getElementById('addHerbSearchResults').innerHTML = '';
        }

        // 添加药材到药方
        document.getElementById('addToPrescription').addEventListener('click', function() {
            const query = document.getElementById('herbSearch').value.trim();
            if (query) {
                fetch(`search.php?query=${encodeURIComponent(query)}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.length > 0) {
                            const herb = data[0];
                            const pricePerGram = calculatePricePerGram(herb);
                            const itemHtml = `
                                <div class="prescription-item d-flex align-items-center" data-name="${herb.name}">
                                    <div class="fw-bold me-2" style="min-width: 120px;">${herb.name}</div>
                                    <div class="flex-grow-1">
                                        <input type="number" class="form-control form-control-sm weight-input" 
                                               value="100" min="1" step="1" placeholder="用量(g)">
                                    </div>
                                    <div class="ms-2 text-nowrap">
                                        <span class="price-per-gram">¥${pricePerGram.toFixed(2)}/g</span>
                                    </div>
                                    <div class="ms-3 text-end" style="min-width: 80px;">
                                        <span class="item-total">¥${(pricePerGram * 100).toFixed(2)}</span>
                                    </div>
                                    <button class="btn btn-sm btn-outline-danger ms-3 remove-item">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </div>
                            `;
                            document.getElementById('prescriptionItems').innerHTML += itemHtml;
                            updateTotal();
                            document.getElementById('herbSearch').value = '';
                        }
                    });
            }
        });

        // 添加药材到药方（在添加药材模态框中）
        document.getElementById('addHerbAddToPrescription').addEventListener('click', function() {
            const query = document.getElementById('addHerbHerbSearch').value.trim();
            if (query) {
                fetch(`search.php?query=${encodeURIComponent(query)}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.length > 0) {
                            const herb = data[0];
                            const pricePerGram = calculatePricePerGram(herb);
                            const itemHtml = `
                                <div class="prescription-item d-flex align-items-center" data-name="${herb.name}">
                                    <div class="fw-bold me-2" style="min-width: 120px;">${herb.name}</div>
                                    <div class="flex-grow-1">
                                        <input type="number" class="form-control form-control-sm weight-input" 
                                               value="100" min="1" step="1" placeholder="用量(g)">
                                    </div>
                                    <div class="ms-2 text-nowrap">
                                        <span class="price-per-gram">¥${pricePerGram.toFixed(2)}/g</span>
                                    </div>
                                    <div class="ms-3 text-end" style="min-width: 80px;">
                                        <span class="item-total">¥${(pricePerGram * 100).toFixed(2)}</span>
                                    </div>
                                    <button class="btn btn-sm btn-outline-danger ms-3 remove-item">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </div>
                            `;
                            document.getElementById('addHerbPrescriptionItems').innerHTML += itemHtml;
                            updateAddHerbTotal();
                            document.getElementById('addHerbHerbSearch').value = '';
                        }
                    });
            }
        });

        // 更新总计
        function updateTotal() {
            let total = 0;
            document.querySelectorAll('.prescription-item').forEach(item => {
                const weight = parseFloat(item.querySelector('.weight-input').value) || 0;
                const pricePerGram = parseFloat(item.querySelector('.price-per-gram').textContent.replace('¥', ''));
                const itemTotal = weight * pricePerGram;
                item.querySelector('.item-total').textContent = `¥${itemTotal.toFixed(2)}`;
                total += itemTotal;
            });
            document.getElementById('prescriptionTotal').textContent = `¥${total.toFixed(2)}`;
        }

        // 更新添加药材模态框中的总计
        function updateAddHerbTotal() {
            let total = 0;
            document.querySelectorAll('#addHerbPrescriptionItems .prescription-item').forEach(item => {
                const weight = parseFloat(item.querySelector('.weight-input').value) || 0;
                const pricePerGram = parseFloat(item.querySelector('.price-per-gram').textContent.replace('¥', ''));
                const itemTotal = weight * pricePerGram;
                item.querySelector('.item-total').textContent = `¥${itemTotal.toFixed(2)}`;
                total += itemTotal;
            });
            document.getElementById('addHerbPrescriptionTotal').textContent = `¥${total.toFixed(2)}`;
        }

        // 批量解析药方
        function parseBatchPrescription(inputText) {
            if (!inputText.trim()) {
                showAlert('warning', '请输入药方内容');
                return;
            }
            
            // 清空现有药方，避免重复添加
            document.getElementById('prescriptionItems').innerHTML = '';
            
            // 预处理输入文本：移除括号内容、注释等
            let cleanedText = inputText
                .replace(/（[^）]*）/g, '') // 移除中文括号内容
                .replace(/\([^)]*\)/g, '') // 移除英文括号内容
                .replace(/[，,]/g, ',') // 统一逗号
                .replace(/\s+/g, ' ') // 统一空格
                .trim();
            
            // 清理输入文本，支持多种分隔符
            const lines = cleanedText.split(/[,，\s\n]+/).filter(line => line.trim());
            let successCount = 0;
            let errorCount = 0;
            let errorMessages = [];
            let processedLines = [];
            
            console.log('原始输入:', inputText);
            console.log('清理后文本:', cleanedText);
            console.log('分割后行数:', lines);
            
            lines.forEach((line, index) => {
                const trimmedLine = line.trim();
                if (!trimmedLine) return;
                
                // 解析药材名和用量，支持多种格式
                // 格式1: 药材名+数字+g (如: 西洋参90g)
                // 格式2: 药材名+数字 (如: 西洋参90)
                // 格式3: 药材名 (如: 西洋参，默认用量100g)
                let herbName, weight;
                
                // 尝试匹配 "药材名+数字+g" 格式
                const match1 = trimmedLine.match(/^(.+?)(\d+(?:\.\d+)?)g$/);
                if (match1) {
                    herbName = match1[1].trim();
                    weight = parseFloat(match1[2]);
                } else {
                    // 尝试匹配 "药材名+数字" 格式
                    const match2 = trimmedLine.match(/^(.+?)(\d+(?:\.\d+)?)$/);
                    if (match2) {
                        herbName = match2[1].trim();
                        weight = parseFloat(match2[2]);
                    } else {
                        // 默认格式，假设整个字符串都是药材名
                        herbName = trimmedLine;
                        weight = 100; // 默认用量100g
                    }
                }
                
                // 清理药材名称（移除多余空格、特殊字符等）
                herbName = herbName.replace(/^\s+|\s+$/g, '').replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, '');
                
                if (herbName && weight > 0) {
                    processedLines.push({ herbName, weight, originalLine: trimmedLine });
                    
                    // 查找药材信息
                    fetch(`search.php?query=${encodeURIComponent(herbName)}`)
                        .then(response => response.json())
                        .then(data => {
                            if (data.length > 0) {
                                const herb = data[0];
                                const pricePerGram = calculatePricePerGram(herb);
                                
                                // 添加到药方中
                                const itemHtml = `
                                    <div class="prescription-item d-flex align-items-center" data-name="${herb.name}">
                                        <div class="fw-bold me-2" style="min-width: 120px;">${herb.name}</div>
                                        <div class="flex-grow-1">
                                            <input type="number" class="form-control form-control-sm weight-input" 
                                                   value="${weight}" min="1" step="1" placeholder="用量(g)">
                                        </div>
                                        <div class="ms-2 text-nowrap">
                                            <span class="price-per-gram">¥${pricePerGram.toFixed(2)}/g</span>
                                        </div>
                                        <div class="ms-3 text-end" style="min-width: 80px;">
                                            <span class="item-total">¥${(pricePerGram * weight).toFixed(2)}</span>
                                        </div>
                                        <button class="btn btn-sm btn-outline-danger ms-3 remove-item">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                `;
                                document.getElementById('prescriptionItems').innerHTML += itemHtml;
                                successCount++;
                                
                                // 更新总计
                                updateTotal();
                            } else {
                                errorCount++;
                                errorMessages.push(`未找到药材: ${herbName} (原文本: ${trimmedLine})`);
                            }
                        })
                        .catch(error => {
                            errorCount++;
                            errorMessages.push(`查询失败: ${herbName} (原文本: ${trimmedLine})`);
                        });
                } else {
                    errorCount++;
                    errorMessages.push(`格式错误: ${trimmedLine}`);
                }
            });
            
            // 显示结果提示
            setTimeout(() => {
                let message = `成功添加 ${successCount} 味药材`;
                if (errorCount > 0) {
                    message += `，${errorCount} 味药材添加失败`;
                    if (errorMessages.length > 0) {
                        message += `\n\n失败详情:`;
                        errorMessages.forEach((error, index) => {
                            if (index < 5) { // 最多显示5个错误
                                message += `\n${index + 1}. ${error}`;
                            }
                        });
                        if (errorMessages.length > 5) {
                            message += `\n... 还有 ${errorMessages.length - 5} 个错误`;
                        }
                    }
                }
                
                // 显示处理统计
                message += `\n\n处理统计:`;
                message += `\n- 原始输入: ${inputText.length} 字符`;
                message += `\n- 清理后: ${cleanedText.length} 字符`;
                message += `\n- 识别到: ${lines.length} 个药材`;
                message += `\n- 成功: ${successCount} 个`;
                message += `\n- 失败: ${errorCount} 个`;
                
                if (errorCount > 0) {
                    showAlert('warning', message);
                } else {
                    showAlert('success', message);
                }
            }, 500);
        }
        
        // 绑定事件
        document.addEventListener('click', function(e) {
            // 删除药方项
            if (e.target.closest('.remove-item')) {
                const prescriptionItem = e.target.closest('.prescription-item');
                prescriptionItem.remove();
                
                // 判断是在哪个模态框中，调用相应的更新函数
                if (prescriptionItem.closest('#addHerbPrescriptionItems')) {
                    updateAddHerbTotal();
                } else {
                    updateTotal();
                }
            }
            
            // 编辑药材
            if (e.target.closest('.edit-btn')) {
                const herbId = e.target.closest('.edit-btn').dataset.id;
                openEditModal(herbId);
            }
            
            // 删除药材
            if (e.target.closest('.delete-btn')) {
                const herbId = e.target.closest('.delete-btn').dataset.id;
                if (confirm('确定要删除这个药材吗？')) {
                    fetch(`delete_herb.php?id=${herbId}`, { method: 'POST' })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                e.target.closest('.col').remove();
                                showAlert('success', '药材删除成功！');
                            } else {
                                showAlert('danger', '删除失败: ' + data.message);
                            }
                        });
                }
            }
        });

        // 更新页面上的药材数据
        function updateHerbOnPage(updatedHerb) {
            // 找到对应的药材卡片
            const herbCard = document.querySelector(`[data-herb-id="${updatedHerb.id}"]`);
            if (herbCard) {
                // 更新药材名称
                const nameElement = herbCard.querySelector('.card-title');
                if (nameElement) {
                    nameElement.textContent = updatedHerb.name;
                }
                
                // 更新价格信息
                const priceElement = herbCard.querySelector('.price-info');
                if (priceElement) {
                    let priceText = '';
                    if (updatedHerb.sale_price) {
                        priceText += `售价: ¥${updatedHerb.sale_price}`;
                    }
                    if (updatedHerb.purchase_price) {
                        priceText += priceText ? ` | 进价: ¥${updatedHerb.purchase_price}` : `进价: ¥${updatedHerb.purchase_price}`;
                    }
                    if (updatedHerb.category_price) {
                        priceText += priceText ? ` | 类目价: ¥${updatedHerb.category_price}` : `类目价: ¥${updatedHerb.category_price}`;
                    }
                    priceElement.textContent = priceText || '价格未设置';
                }
                
                // 更新功效
                const effectsElement = herbCard.querySelector('.effects-info');
                if (effectsElement) {
                    effectsElement.textContent = updatedHerb.effects || '功效未设置';
                }
                
                // 更新禁忌
                const contraindicationsElement = herbCard.querySelector('.contraindications-info');
                if (contraindicationsElement) {
                    contraindicationsElement.textContent = updatedHerb.contraindications || '禁忌未设置';
                }
                
                // 更新运费信息
                const shippingElement = herbCard.querySelector('.shipping-info');
                if (shippingElement) {
                    shippingElement.textContent = updatedHerb.shipping || '包邮';
                }
                
                // 更新每克价格（需要重新计算）
                const pricePerGramElement = herbCard.querySelector('.price-badge');
                if (pricePerGramElement) {
                    // 重新计算每克价格
                    let newPricePerGram = 0;
                    if (updatedHerb.sale_price) {
                        newPricePerGram = (updatedHerb.sale_price * 1.2) / 10;
                    } else if (updatedHerb.purchase_price) {
                        newPricePerGram = (updatedHerb.purchase_price * 1.2) / 10;
                    } else if (updatedHerb.category_price) {
                        newPricePerGram = updatedHerb.category_price / 250;
                    }
                    pricePerGramElement.textContent = `¥${newPricePerGram.toFixed(2)}/g`;
                }
            }
        }

        // 打开编辑模态框
        function openEditModal(herbId) {
            // 获取药材数据
            const url = `search.php?query=&id=${herbId}`;
            
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data.length > 0) {
                        const herb = data[0];
                        fillEditForm(herb);
                        const editModal = new bootstrap.Modal(document.getElementById('editHerbModal'));
                        editModal.show();
                    } else {
                        showAlert('danger', '未找到药材信息');
                    }
                })
                .catch(error => {
                    console.error('获取药材信息失败:', error);
                    showAlert('danger', '获取药材信息失败');
                });
        }

        // 填充编辑表单
        function fillEditForm(herb) {
            document.getElementById('editHerbId').value = herb.id;
            document.getElementById('editHerbName').value = herb.name;
            document.getElementById('editPurchasePrice').value = herb.purchase_price || '';
            document.getElementById('editSalePrice').value = herb.sale_price || '';
            document.getElementById('editShipping').value = herb.shipping;
            document.getElementById('editCategoryPrice').value = herb.category_price || '';
            document.getElementById('editEffects').value = herb.effects || '';
            document.getElementById('editContraindications').value = herb.contraindications || '';
        }

        // 编辑药材表单提交
        document.getElementById('editHerbForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.textContent;
            
            // 显示加载状态
            submitBtn.disabled = true;
            submitBtn.textContent = '保存中...';
            
            fetch('edit_herb.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showAlert('success', data.message);
                    // 关闭模态框
                    const editModal = bootstrap.Modal.getInstance(document.getElementById('editHerbModal'));
                    editModal.hide();
                    
                    // 更新页面上的药材数据，不刷新页面
                    updateHerbOnPage(data.data);
                } else {
                    let errorMessage = data.message;
                    if (data.errors) {
                        errorMessage += ': ' + Object.values(data.errors).join(', ');
                    }
                    showAlert('danger', errorMessage);
                }
            })
            .catch(error => {
                console.error('编辑药材失败:', error);
                showAlert('danger', '编辑药材失败，请重试');
            })
            .finally(() => {
                // 恢复按钮状态
                submitBtn.disabled = false;
                submitBtn.textContent = originalText;
            });
        });

        // 添加药材表单提交
        document.getElementById('addHerbForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.textContent;
            
            // 显示加载状态
            submitBtn.disabled = true;
            submitBtn.textContent = '保存中...';
            
            fetch('add_herb.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showAlert('success', data.message);
                    
                    // 将新添加的药材自动添加到药方中
                    const herbName = formData.get('name');
                    const salePrice = formData.get('sale_price');
                    const purchasePrice = formData.get('purchase_price');
                    const categoryPrice = formData.get('category_price');
                    
                    // 计算每克价格
                    let pricePerGram = 0;
                    if (salePrice) {
                        pricePerGram = salePrice / 10;
                    } else if (categoryPrice) {
                        pricePerGram = categoryPrice / 250;
                    } else if (purchasePrice) {
                        pricePerGram = (purchasePrice * 1.2) / 10;
                    }
                    
                    if (pricePerGram > 0) {
                        const itemHtml = `
                            <div class="prescription-item d-flex align-items-center" data-name="${herbName}">
                                <div class="fw-bold me-2" style="min-width: 120px;">${herbName}</div>
                                <div class="flex-grow-1">
                                    <input type="number" class="form-control form-control-sm weight-input" 
                                           value="100" min="1" step="1" placeholder="用量(g)">
                                </div>
                                <div class="ms-2 text-nowrap">
                                    <span class="price-per-gram">¥${pricePerGram.toFixed(2)}/g</span>
                                </div>
                                <div class="ms-3 text-end" style="min-width: 80px;">
                                    <span class="item-total">¥${(pricePerGram * 100).toFixed(2)}</span>
                                </div>
                                <button class="btn btn-sm btn-outline-danger ms-3 remove-item">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </div>
                        `;
                        document.getElementById('addHerbPrescriptionItems').innerHTML += itemHtml;
                        updateAddHerbTotal();
                        
                        // 显示提示信息
                        showAlert('info', `已将新添加的药材"${herbName}"添加到药方中，用量设为100g`);
                    }
                    
                    // 重置表单
                    this.reset();
                    // 关闭模态框
                    const addModal = bootstrap.Modal.getInstance(document.getElementById('addHerbModal'));
                    addModal.hide();
                    // 跳转到主页
                    setTimeout(() => {
                        window.location.href = 'index.php';
                    }, 1500);
                } else {
                    let errorMessage = data.message;
                    if (data.errors) {
                        errorMessage += ': ' + Object.values(data.errors).join(', ');
                    }
                    showAlert('danger', errorMessage);
                }
            })
            .catch(error => {
                console.error('添加药材失败:', error);
                showAlert('danger', '添加药材失败，请重试');
            })
            .finally(() => {
                // 恢复按钮状态
                submitBtn.disabled = false;
                submitBtn.textContent = originalText;
            });
        });

        // 重量输入变化时更新价格
        document.addEventListener('input', function(e) {
            if (e.target.classList.contains('weight-input')) {
                // 判断是在哪个模态框中，调用相应的更新函数
                if (e.target.closest('#addHerbPrescriptionItems')) {
                    updateAddHerbTotal();
                } else {
                    updateTotal();
                }
            }
        });

        // 双击药方项编辑用量
        document.addEventListener('dblclick', function(e) {
            if (e.target.closest('.prescription-item')) {
                const weightInput = e.target.closest('.prescription-item').querySelector('.weight-input');
                if (weightInput) {
                    weightInput.focus();
                    weightInput.select();
                }
            }
        });

        // 重新计算按钮
        document.getElementById('calculateBtn').addEventListener('click', updateTotal);

        // 清空添加药材模态框中的药方
        document.getElementById('clearAddHerbPrescription').addEventListener('click', function() {
            document.getElementById('addHerbPrescriptionItems').innerHTML = '';
            updateAddHerbTotal();
        });
        
        // 批量解析药方按钮
        document.getElementById('parseBatchPrescription').addEventListener('click', function() {
            const inputText = document.getElementById('batchPrescriptionInput').value;
            parseBatchPrescription(inputText);
        });
        
        // 清空批量输入
        document.getElementById('clearBatchInput').addEventListener('click', function() {
            document.getElementById('batchPrescriptionInput').value = '';
        });

        // 监听药方计算模态框关闭事件，自动清空内容
        document.getElementById('prescriptionModal').addEventListener('hidden.bs.modal', function() {
            // 清空药方项目
            document.getElementById('prescriptionItems').innerHTML = '';
            // 清空批量输入框
            document.getElementById('batchPrescriptionInput').value = '';
            // 清空单个药材搜索框
            document.getElementById('herbSearch').value = '';
            // 清空搜索结果
            document.getElementById('searchResults').innerHTML = '';
            // 重置总计
            document.getElementById('prescriptionTotal').textContent = '¥0.00';
        });

        // 初始化
        updateTotal();
    </script>
</body>
</html>